<?php
class ModelTotalPromotion extends Model {
	public function getTotal(&$total_data, &$total, &$taxes) {
		if (!isset($this->session->data['promotion'])) return;

		$this->language->load('total/promotion');
		$promotion = $this->session->data['promotion'];
		$promotion_data = array();

		foreach ($this->cart->getProducts() as $product) {			
			$quantity_data[$product['product_id']] = array($product['quantity'], $product['price']);
		}

		foreach ($promotion as $product_id => $related) {
			foreach ($related as $related_id => $price) {
				if (isset($quantity_data[$product_id]) && isset($quantity_data[$related_id]) && $quantity_data[$related_id][1] > $price) {
					if (isset($promotion_data[$related_id])) {
						$promotion_data[$related_id][0] += $quantity_data[$product_id][0];
					}
					else {
						$promotion_data[$related_id] = array($quantity_data[$product_id][0], $quantity_data[$related_id][1] - $price);
					}
				}
			}
		}

		$discount = 0;
		foreach ($promotion_data as $related_id => $promotion) {
			$discount += min($promotion[0], $quantity_data[$related_id][0]) * $promotion[1];
		}

		if ($discount) {
			$total -= $discount;
			$total_data[] = array(
				'code'       => 'promotion',
    			'title'      => $this->language->get('text_promotion'),
    			'text'       => $this->currency->format(-$discount),
    			'value'      => -$discount,
				'sort_order' => C('promotion_sort_order')
  			);
		}
	}
}